#include "Thread.h"

using std::cout;
using std::endl;
#define NUM 4

// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int ticketnum = 10000;

class ThreadDate
{

public:
    std::string _name;
    pthread_mutex_t *lock_ptr;
};
void Ticket(ThreadDate &td)
{
    while (1)
    {
        pthread_mutex_lock(td.lock_ptr);
        if (ticketnum > 0)
        {
            usleep(1000);
            cout << "get a new ticket " << td._name.c_str() << ":" << ticketnum-- << endl;
            pthread_mutex_unlock(td.lock_ptr);

            usleep(50);
        }
        else
        {
            pthread_mutex_unlock(td.lock_ptr);
            break;
        }
    }
}
int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr);
    std::vector<ThreadModule::Thread<ThreadDate>> threads;
    for (int i = 0; i < NUM; i++)
    {
        ThreadDate *td = new ThreadDate();
        td->lock_ptr = &lock;
        threads.emplace_back(Ticket, *td);
        td->_name = threads.back().Name();
    }

    for (auto &thread : threads)
    {
        thread.Start();
    }

    // 3. 等待线程
    for (auto &thread : threads)
    {
        thread.Join();
    }

    pthread_mutex_destroy(&lock);

    return 0;
}